import { isArrayBuffer } from "@smithy/is-array-buffer";
import { buffer } from "@kit.ArkTS";

/**
 * @internal
 */
export const fromArrayBuffer = (input: ArrayBuffer, offset = 0, length: number = input.byteLength - offset): buffer.Buffer => {
  if (!isArrayBuffer(input)) {
    throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
  }

  return buffer.from(input, offset, length);
};

/**
 * @internal
 */
export type StringEncoding = buffer.BufferEncoding;

/**
 * @internal
 */
export const fromString = (input: string, encoding?: StringEncoding): buffer.Buffer => {
  if (typeof input !== "string") {
    throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
  }

  return encoding ? buffer.from(input, encoding) : buffer.from(input);
};
